const rp  = require("request-promise");
const http = require('http');
const request = require("request");
const redis = require("../config/baseRedis.js");
const SHA = require('sha1');
const config = require('../config/'+process.env.NODE_ENV);
//微信的作用域
let wechat = function(args){
    if(!(this instanceof wechat)){
        return new wechat(args);
    }
};
//token 微信定义的
global.weToken = "fuwang07diy";
/**
 * 获取微信access_token,缓存
 */
wechat.getToken = async function()
{   
    //创建redis链接
    let client = await redis.wxRedisclient();
    let access_token =  await
    client.get("access_token",function(err,token){
        return token;
    });

    if(access_token != undefined && access_token !="" && access_token != null)
    {
        console.log("access_token:%s",access_token);
        return await access_token;
    }
    // const AppID = "wxaf6358962d71161f";
    const AppID = config.AppId;
    //AppSecret
    // const AppSecret = "7a89b3c8d1b8b8be9bac9095b27da9f8";
    const AppSecret = config.AppSecret;
    let uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+AppID+"&secret="+AppSecret;
    let options = {
      method: 'GET',
      uri: uri,
      form: {
         
      },     
    };
    let result = "";
    await rp(options).then(function (body) {
                result = body;
        })
        .catch(function (err) {
            result = err;
        });
   result = JSON.parse(result);
   access_token = result.access_token;
   console.log("access_token:%s",access_token);
   //做缓存
   client.set("access_token", access_token);
   client.expire('access_token', 7000)//设置失效时间精确到m,过期时间7000秒
   return await access_token;  
}

/**
 * 微信验证签名
 * @param {*Int M} timestamp 当前时间戳
 * @param {*Int M} nonce 随机数 
 * @param {*String M} signature 签名文件
 */
wechat.isTrueSign = function(timestamp,nonce,signature)
{
    let sign = [global.weToken,timestamp,nonce].sort().join('');//生成签名
    let shaSign = SHA(sign);
    console.log("shaSign:%s",shaSign);
    if(shaSign === signature){
        return true;
    }else{
        return false;
    }
}

/**
 * 推送短信By带参数的二维码扫入，微信关注
 * @param {*String M} ToUserName 收到的账号
 * @param {*String M} FromUserName 发送的账号
 * @param {*String M} userId 用户ID
 */
wechat.getXmlContentBySubscribe = function(ToUserName,FromUserName,userId)
{
    let wxDomain = config.wxDomain;console.log("wxDomain:%s",wxDomain);
    let content = '主人，你怎么才来，哼[右哼哼]\n'+
                  '想理财，当然朝我看[得意]\n'+
                  ' ↓↓↓   \n'+
                  '【零】钱理财百元起投新平台\n '+
                  '【钱】所未有环保理财新观念\n '+
                  '【袋】来财富与安全双重保障\n '+
                  '猛戳这里→【<a href="http://wx.lingqd.com/prepare?inviteCode='+userId+'">立即注册</a>】\n '+
                  '点击下方活动，开始你的土豪进阶\n '+
                  '• 新人专享：<a href="http://wx.lingqd.com">点此进入</a>\n '+
                  '放心戳，我不怕疼[可怜]。\n';
    let xmlStr  = "<xml> "+
                        "<ToUserName><![CDATA["+ToUserName+"]]></ToUserName> "+
                        "<FromUserName><![CDATA["+FromUserName+"]]></FromUserName> "+
                        "<CreateTime>"+Date.now()+"</CreateTime> "+
                        "<MsgType><![CDATA[text]]></MsgType> "+
                        "<Content><![CDATA["+content+"]]></Content> "+
                        "</xml>";
    return xmlStr;
}
/**
 * 获取客服电话
 */
wechat.getXmlContentByClick = function(ToUserName,FromUserName)
{
    let content = '零钱袋客户服务电话\n'+
                  '<a href="tel:400-836-7077">400-836-7077</a>\n'+
                  '公司外拨电话\n'+
                  '<a href="tel:021-80392953">021-80392953</a>\n'+
                  '客服工作时间：\n'+
                  '9:30-17:30';
    let xmlStr  = "<xml> "+
                        "<ToUserName><![CDATA["+ToUserName+"]]></ToUserName> "+
                        "<FromUserName><![CDATA["+FromUserName+"]]></FromUserName> "+
                        "<CreateTime>"+Date.now()+"</CreateTime> "+
                        "<MsgType><![CDATA[text]]></MsgType> "+
                        "<Content><![CDATA["+content+"]]></Content> "+
                        "</xml>";
    return xmlStr;
}
/**
 * 自定义菜单生成
 */
wechat.getCustomMenu = function ()
{
    console.log(1);
    let wxDomain = config.wxDomain;
    let webDomain = config.webDomain;
    let menuJson = {
        "button":[
            {
                "type":"view",
                "name":"开始投资",
                "url":'http://wx.lingqd.com'
            },
            {
                "name":"关于我们",
                "sub_button":[
                    {
                        "type":"view",
                        "name":"零钱袋介绍",
                        "url":"http://wx.lingqd.com/more/company"
                    },
                    {
                        "type":"view",
                        "name":"风控保障",
                        "url":"http://wx.lingqd.com/more/fund_security"
                    },
                    {
                        "type":"click",
			            "name":"客服电话",
			            "key":"V1001_service"
                    }
                ]
            },
            {
                "type":"view",
                "name":"app下载",
                "url":"http://wx.lingqd.com/wxdown/dl"
            }
        ]
    };
    return menuJson;
}

wechat.toDecimal2 = function (x) {    
        var f = parseFloat(x);    
        if (isNaN(f)) {    
            return false;    
        }    
        var f = Math.round(x*100)/100;    
        var s = f.toString();    
        var rs = s.indexOf('.');    
        if (rs < 0) {    
            rs = s.length;    
            s += '.';    
        }    
        while (s.length <= rs + 2) {    
            s += '0';    
        }    
        return s;    
    }    
module.exports = wechat;